import 'dart:math';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_base_widget/code7/provider/demo1/time_counter_model.dart';
import 'package:provider/provider.dart';
import 'dart:async';

///代码清单 7-8-2
///lib/code7/provider/demo1/provider_mult.dart
void main() => runApp(
      const MaterialApp(
        ///默认的首页面
        home: TestProviderMulPage(),
      ),
    );

class TestProviderMulPage extends StatelessWidget {
  const TestProviderMulPage({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    ///组合多个Provider
    return MultiProvider(
      providers: [
        ///计时器
        ChangeNotifierProvider(
          create: (BuildContext context) {
            return TimeCounterModel();
          },
        ),

        ///随机数据
        ChangeNotifierProvider(
          create: (BuildContext context) {
            return RandomNumberModel();
          },
        )
      ],
      child: const TestConsumerTimePage(),
    );
  }
}

///代码清单 7-8-3
class TestConsumerTimePage extends StatefulWidget {
  const TestConsumerTimePage({Key? key}) : super(key: key);
  @override
  State<StatefulWidget> createState() {
    return _TestABPageState();
  }
}

class _TestABPageState extends State {
  ///计时器
  Timer? _timer;
  @override
  void initState() {
    super.initState();
    ///间隔1秒执行时间
    _timer = Timer.periodic(Duration(milliseconds: 1000), (timer) {
      ///发送事件
      Provider.of<TimeCounterModel>(context, listen: false).getCurrentTime();
      Provider.of<RandomNumberModel>(context, listen: false).testRandom(); //2
    });
  }

  @override
  Widget build(BuildContext context) {
    ///页面主体脚手架
    return const Scaffold(
      body: CPage(),
    );
  }

  @override
  void dispose() {
    super.dispose();
    ///取消计时器
    if(_timer!=null) {
      _timer!.cancel();
    }
  }
}
///代码清单 7-8-4
class CPage extends StatelessWidget{
  const CPage({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    ///通过 Consumer2 来同时监听处理两个结果
    return Consumer2<TimeCounterModel, RandomNumberModel>(
      ///参数 value 为 TimeCounterModel 类型
      ///参数 value2 为 RandomNumberModel 类型
      builder: (BuildContext context, value, value2, Widget? child) {
        return Container(
          margin: EdgeInsets.only(left: 12, top: 12),
          child: Text(
            '当前时间 ${value.formatTime} 随机数 ${value2.randomNumber}',
            style: TextStyle(fontSize: 22.0, color: Colors.red),
          ),
        );
      },
    );
  }
}

///代码清单 7-8-1
///lib/code7/provider/demo1/provider_mult.dart
class RandomNumberModel with ChangeNotifier {
  int _randomNumber = 0;
  ///指定数据
  void testNumber(int number) {
    _randomNumber = number;
    notifyListeners(); //2
  }
  ///随机数据
  void testRandom() {
    _randomNumber = Random().nextInt(100);
    notifyListeners();
  }
  get randomNumber => _randomNumber; //3
}
